#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace std;

void Usage(string proc)
{
    cout << "Usage: " << proc << " + ip + port" << endl;
}
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(4);
    }
    uint16_t serverport = stoi(argv[2]);
    string serverip = argv[1];

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        cout << "sock create fail" << endl;
    }

    // 填充结构体字段
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    // 直接通信
    string message;
    while(true)
    {
        cout << "Please message# ";
        getline(cin, message);
        sendto(sockfd, message.c_str(), sizeof(message)-1, 0, (struct sockaddr*)&server, sizeof(server));

        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int n = recvfrom(sockfd, buffer, strlen(buffer), 0, (struct sockaddr*)&peer, &len);
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "server echo# " << buffer << endl;
        }
    }

    return 0;
}